package com.myth.mysql2dm.utils;

import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author myth
 */
public class DmUtils {

    private final static Logger LOGGER = LoggerFactory.getLogger(DmUtils.class);

    /**
     * 将Mysql语法适配为DM语法
     *
     * @param originalSql
     * @return
     */
    public static String modifySql(String originalSql) {
        try {
            SQLStatement sqlStatement = SQLUtils.parseSingleMysqlStatement(originalSql);
            DmSupportVisitor visitor = new DmSupportVisitor();
            sqlStatement.accept(visitor);
            String modifiedSql = sqlStatement.toString();
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(StrUtil.format("DMAdapter Modify Success -->\n" +
                        "Origin Sql: \n" +
                        "{}, \n" +
                        "Actual Sql: \n" +
                        "{}", originalSql, modifiedSql));
            } else {
                LOGGER.error(StrUtil.format("DMAdapter Modify Success -->\n" +
                        "Actual Sql: \n" +
                        "{}", modifiedSql));
            }
            return modifiedSql;
        } catch (Exception e) {
            LOGGER.error(StrUtil.format("DMAdapter Modify Failed -->\n" +
                    "Origin Sql: \n" +
                    "{}", originalSql), e);
            return originalSql;
        }
    }

    /**
     * 达梦不支持日期格式函数参数为 %H:00形式, 需要加上", 改成%H":00"
     *
     * @param content
     * @return
     */
    public static String resolveForDateFormat(String content) {
        boolean flag = false;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < content.length(); i++) {
            char thisChar = content.charAt(i);
            if (thisChar == '%') {
                if (i == 0) {
                    sb.append(thisChar);
                } else {
                    sb.append("\"").append(thisChar);
                }
                flag = true;
            } else {
                if (flag) {
                    if (i == content.length() - 1) {
                        sb.append(thisChar);
                    } else {
                        sb.append(thisChar).append("\"");
                    }
                } else {
                    if (i == content.length() - 1) {
                        sb.append(thisChar).append("\"");
                    } else {
                        sb.append(thisChar);
                    }

                }
                flag = false;
            }
        }
        return sb.toString();
    }
}
